package com.aliyun.messagemgt.application.service.Impl;

import com.aliyun.messagemgt.common.annotation.PagingAnnotation;
import com.aliyun.messagemgt.application.service.SmsSignService;
import com.aliyun.messagemgt.dto.vo.SmsSignVO;
import com.aliyun.messagemgt.domain.repository.SmsSignRepository;
import com.aliyun.messagemgt.common.enums.BusinessErrorCode;
import com.aliyun.messagemgt.common.dto.response.ResultMap;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author: li.wy
 * @create: 2020-10-29
 **/
@Service
public class SmsSignServiceImpl implements SmsSignService {
    @Autowired
    private SmsSignRepository smsSignRepository;

    @Override
    @PagingAnnotation
    public Object getSmsSigns(Integer templateId) {
        List<SmsSignVO> smsSigns = smsSignRepository.getSmsSigns(templateId);
        PageInfo pageInfo = new PageInfo(smsSigns);
        return pageInfo;
    }

    @Override
    public Object insert(SmsSignVO smsSignVo) {
        // signName 不能为空
        if (!checkParam(smsSignVo)) {
            return new ResultMap(ResultMap.ERROR, BusinessErrorCode.SMS_SIGN_NAME_EMPTY.getMessage());
        }
        int insert = smsSignRepository.insert(smsSignVo);
        if (insert >= 0) {
            return ResultMap.success(smsSignVo);
        } else {
            return new ResultMap(ResultMap.ERROR, BusinessErrorCode.FAILURE_QUERY.getMessage());
        }
    }

    @Override
    public Object update(SmsSignVO smsSignVo) {
        // code name 不能为空
        if (!checkParam(smsSignVo)) {
            return new ResultMap(ResultMap.ERROR, BusinessErrorCode.SMS_SIGN_NAME_EMPTY.getMessage());
        }
        int i = smsSignRepository.updateById(smsSignVo);
        if (i >= 0) {
            return ResultMap.success(smsSignVo);
        } else {
            return new ResultMap(ResultMap.ERROR, BusinessErrorCode.FAILURE_QUERY.getMessage());
        }
    }

    @Override
    public Object deleteById(Integer id, String accountInfo) {
        if (null == id) {
            return new ResultMap(ResultMap.ERROR, BusinessErrorCode.SMS_SIGN_ID_EMPTY.getMessage());
        }

        int templateBySmsSign = smsSignRepository.findTemplateBySmsSign(id);
        if (templateBySmsSign > 0) {
            return new ResultMap(ResultMap.ERROR, BusinessErrorCode.SMS_SIGN_DELETE.getMessage());
        }

        int i = smsSignRepository.deleteById(id, accountInfo);
        if (i >= 0) {
            return ResultMap.success(id);
        } else {
            return new ResultMap(ResultMap.ERROR, BusinessErrorCode.FAILURE_QUERY.getMessage());
        }
    }

    @Override
    public Object findAll() {
        return smsSignRepository.findAll();
    }

    private static boolean checkParam(SmsSignVO smsSignVo) {
        return !StringUtils.isEmpty(smsSignVo.getSignName());
    }
}
